import type { UserInfo, ILoginApp } from '/#/store';
import type { ErrorMessageMode } from '/#/axios';
import { defineStore } from 'pinia';
import { store } from '/@/store';
import { RoleEnum } from '/@/enums/roleEnum';
import { PageEnum } from '/@/enums/pageEnum';
import { ROLES_KEY, TOKEN_KEY, USER_INFO_KEY, LOGIN_APP_KEY, CLIENT_ID_KEY } from '/@/enums/cacheEnum';
import { getAuthCache, setAuthCache } from '/@/utils/auth';
import { LoginParams } from '/@/api/sys/model/userModel';
import { doLogout, getUserInfo, loginApi } from '/@/api/sys/user';
import { getAccessableAppByToken } from '/@/api/user';
import { useI18n } from '/@/hooks/web/useI18n';
import { useMessage } from '/@/hooks/web/useMessage';
import { router } from '/@/router';
import { usePermissionStore } from '/@/store/modules/permission';
import { RouteRecordRaw, createRouter, createWebHashHistory } from 'vue-router';
import { PAGE_NOT_FOUND_ROUTE, FULL_PAGE_NOT_FOUND_ROUTE } from '/@/router/routes/basic';
import { isArray } from '/@/utils/is';
import { useTabs } from '/@/hooks/web/useTabs';
import avatar_m from '/resource/img/avatar_m.png'
import avatar_f from '/resource/img/avatar_f.png'

const { createMessage, createConfirm } = useMessage();

interface UserState {
  userInfo: Nullable<UserInfo>;
  token?: string;
  clientId?: string;
  roleList: RoleEnum[];
  sessionTimeout?: boolean;
  lastUpdateTime: number;
  switchAppVis: Boolean;
  loginApp: ILoginApp;
}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): UserState => ({
    // user info
    userInfo: null,
    // token
    token: undefined,
    // clientId
    clientId: undefined,
    // roleList
    roleList: [],
    // Whether the login expired
    sessionTimeout: false,
    // Last fetch time
    lastUpdateTime: 0,
    switchAppVis: false,
    loginApp: {
      currentId: null,
      clientManagerId: null,
      clientManagerFlag: null,
      accessableList: [],
    }
  }),
  getters: {
    getUserInfo(): UserInfo {
      return this.userInfo || getAuthCache<UserInfo>(USER_INFO_KEY) || {};
    },
    getToken(): string {
      // debugger;
      return this.token || getAuthCache<string>(TOKEN_KEY);
    },
    getClientId(): string {
      // debugger;
      return this.clientId || getAuthCache<string>(CLIENT_ID_KEY);
    },
    getRoleList(): RoleEnum[] {
      return this.roleList.length > 0 ? this.roleList : getAuthCache<RoleEnum[]>(ROLES_KEY);
    },
    getSessionTimeout(): boolean {
      return !!this.sessionTimeout;
    },
    getLastUpdateTime(): number {
      return this.lastUpdateTime;
    },
    getLoginApp(): ILoginApp {
      // debugger;
      return this.loginApp.accessableList.length ? this.loginApp : getAuthCache<ILoginApp>(LOGIN_APP_KEY);
    },
  },
  actions: {
    setToken(info: string | undefined) {
      this.token = info ? info : ''; // for null or undefined value
      setAuthCache(TOKEN_KEY, info);
    },
    setClientId(info: string | undefined) {
      this.clientId = info ? info : ''; // for null or undefined value
      setAuthCache(CLIENT_ID_KEY, info);
    },
    setRoleList(roleList: RoleEnum[]) {
      this.roleList = roleList;
      setAuthCache(ROLES_KEY, roleList);
    },
    setUserInfo(info: UserInfo | null) {
      this.userInfo = info;
      this.lastUpdateTime = new Date().getTime();
      setAuthCache(USER_INFO_KEY, info);
    },
    setLoginApp(p: Omit<ILoginApp, 'clientManagerFlag'>) {
      // debugger;
      this.loginApp = {
        clientManagerFlag: p.accessableList.filter(e => e.clientId == p.currentId)[0]?.clientManagerFlag,
        ...p
      }
      setAuthCache(LOGIN_APP_KEY, this.loginApp);
    },
    
    updateLoginApp(p: ILoginApp) {
      // debugger;
      this.loginApp = p;
      setAuthCache(LOGIN_APP_KEY, p);
    },
    setSessionTimeout(flag: boolean) {
      this.sessionTimeout = flag;
    },
    // setloginWithAppId(appId: number) {
    //   this.loginWithAppId = appId;
    // },
    resetState() {
      this.userInfo = null;
      this.token = '';
      this.roleList = [];
      this.sessionTimeout = false;
      // this.loginWithAppId = null;
    },
    /**
     * @description: login
     */
    async login(
      params: LoginParams & {
        domainAlias?: string,
        goHome?: boolean;
        mode?: ErrorMessageMode;
      },
    ): Promise<any | null> {
      try {
        const { goHome = true, mode, ...loginParams } = params;
        let data = null as any;
        data = await loginApi(loginParams, mode);
        const { code, data: ret } = data;
        if (code == 200) {
          this.setToken(ret.access_token);
          return this.afterLoginAction(goHome);
        } else {
          return false;
        }
      } catch (error) {
        return Promise.reject(error);
      }
    },
    async afterLoginAction(goHome?: boolean): Promise<any | null> {
      if (!this.getToken) return null;
      const appList = await this.getUserAppAction();
      if(appList.length == 0) {
        createMessage({
          message: '请联系管理员添加应用权限',
          duration: 10000,
          type: 'warning'
        })
      }
      // debugger;
      router.replace(PageEnum.BASE_HOME)
      return { appList};
    },
    async getUserInfoAction(): Promise<UserInfo | null> {
      if (!this.getToken) return null;
      const { data } = await getUserInfo();
      const userInfo = {
        userId: data.userId,
        username: data.nickname,
        realName: data.username,
        avatar: data.headImgUrl || (data.sex == 1 ? avatar_m : avatar_f),
        desc: '',
        password: '',
        token: this.getToken,
        roles: []
      };
      const { roles = [] } = userInfo;
      if (isArray(roles)) {
        const roleList = roles.map((item:any) => item.value) as RoleEnum[];
        this.setRoleList(roleList);
      } else {
        userInfo.roles = [];
        this.setRoleList([]);
      }
      this.setUserInfo(userInfo);
      return userInfo;
    },
    async getUserAppAction(): Promise<any | null> {
      if (!this.getToken) return null;
      const { data } = await getAccessableAppByToken({clientId: this.getClientId});
      this.setLoginApp({
        currentId: data.length == 1 ? data[0].clientId : null,
        clientManagerId: data.length == 1 ? data[0]?.clientManagerIds : null,
        accessableList: data || []
      });
      return data;
    },
    /**
     * @description: logout
     */
    async logout(goLogin = false) {
      if (this.getToken) {
        try {
          await doLogout();
        } catch {
          console.log('注销Token失败');
        }
      }
      this.setToken(undefined);
      this.setSessionTimeout(false);
      this.setUserInfo(null);
      this.setLoginApp({
        currentId: null,
        clientManagerId: null,
        accessableList: [],
      })
      goLogin && router.push(PageEnum.BASE_LOGIN);
    },

    /**
     * @description: Confirm before logging out
     */
    confirmLoginOut() {
      const { t } = useI18n();
      createConfirm({
        title: t('sys.app.logoutTip'),
        message: t('sys.app.logoutMessage'),
        onOk: async () => {
          await this.logout(true);
        },
      });
    },

    /**
     * @param {boolean} goHome 是否跳转首页，普通跳转使用
     * @param {boolean} updateSysMenu 是否重新加载路由，只有在切换应用的时候需要用到
     * @desc 这两个任何一个参数是true，都会重新加载路由
    */
    async loginEnd(goHome?: Boolean, updateSysMenu = false) {
      const sessionTimeout = this.sessionTimeout;
      if (sessionTimeout) {
        this.setSessionTimeout(false);
      } else {
        const permissionStore = usePermissionStore();
        let homePath = '';
        if (!permissionStore.isDynamicAddedRoute || updateSysMenu) {
          const routes:any = await permissionStore.buildRoutesAction();
          const rs = createRouter({routes, history: createWebHashHistory(import.meta.env.VITE_PUBLIC_PATH),}).getRoutes();
          rs.sort((a:any, b:any) => {
            return a.meta?.orderNo - b.meta?.orderNo;
          });
          if (rs[0]?.children?.length > 0) { 
            homePath = `${rs[0].path}/${rs[0]?.children[0]?.path}`;
          } else {
            homePath = rs[0].path
          }
          routes.forEach((route) => {
            router.addRoute(route as unknown as RouteRecordRaw);
          });
          router.addRoute(FULL_PAGE_NOT_FOUND_ROUTE as unknown as RouteRecordRaw);
          router.addRoute(PAGE_NOT_FOUND_ROUTE as unknown as RouteRecordRaw);
          permissionStore.setDynamicAddedRoute(true);

          // 切换应用，重新加载的路由首页和当前应用的路由首页一样，需要手动刷新页面，重新请求数据
          if (updateSysMenu && router.currentRoute.value.path == homePath) {
            const { refreshPage } = useTabs(router)
            refreshPage()
            return homePath;
          }
        }
        
        goHome && (await router.replace(homePath || PageEnum.BASE_HOME));
        return homePath;
      }
    }
  },
});

// Need to be used outside the setup
export function useUserStoreWithOut() {
  return useUserStore(store);
}
